package handler

import (
	"fmt"
	"net/http"
	"net/url"
	"strconv"

	"go-file-perception-model/internal/logger"
	"go-file-perception-model/internal/service"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

// SystemHandler 系统处理器
type SystemHandler struct {
	fileService *service.FileService
}

// NewSystemHandler 创建系统处理器实例
func NewSystemHandler(fileService *service.FileService) *SystemHandler {
	return &SystemHandler{
		fileService: fileService,
	}
}

// GetSystemStats 处理获取系统统计信息请求
func (h *SystemHandler) GetSystemStats(c *gin.Context) {
	// 调用服务层获取系统统计信息
	stats, err := h.fileService.GetSystemStats()
	if err != nil {
		logger.Error("Failed to get system stats", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to get system stats",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "System stats retrieved successfully",
		"data":    stats,
	})
}

// GetSystemStatus 处理获取系统状态请求
func (h *SystemHandler) GetSystemStatus(c *gin.Context) {
	// 调用服务层获取系统状态
	status, err := h.fileService.GetSystemStats()
	if err != nil {
		logger.Error("Failed to get system status", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to get system status",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "System status retrieved successfully",
		"data":    status,
	})
}

// GetFileList 处理获取文件列表请求
func (h *SystemHandler) GetFileList(c *gin.Context) {
	directory := c.Query("directory")
	if directory == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Directory parameter is required",
		})
		return
	}

	recursiveStr := c.DefaultQuery("recursive", "false")
	recursive, err := strconv.ParseBool(recursiveStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Invalid recursive parameter",
		})
		return
	}

	// 调用服务层获取文件列表
	files, err := h.fileService.GetFileList(directory, recursive)
	if err != nil {
		logger.Error("Failed to get file list", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to get file list",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "File list retrieved successfully",
		"data":    files,
	})
}

// GetFileContent 处理获取文件内容请求，用于显示原始文件内容，支持相对路径
func (h *SystemHandler) GetFileContent(c *gin.Context) {
	// 获取文件路径参数
	filePath := c.Query("path")
	if filePath == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "File path is required",
		})
		return
	}

	// 对URL编码的文件路径进行解码
	decodedPath, err := url.QueryUnescape(filePath)
	if err != nil {
		logger.Error("Failed to decode file path", zap.String("path", filePath), zap.Error(err))
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Invalid file path encoding",
			"error":   err.Error(),
		})
		return
	}

	// 添加调试信息
	logger.Info("Processing file path", zap.String("original", filePath), zap.String("decoded", decodedPath))
	fmt.Printf("[HANDLER DEBUG] Processing file path: original=%s, decoded=%s\n", filePath, decodedPath)

	// 解析文件路径（处理相对路径）
	fmt.Printf("[HANDLER DEBUG] Calling ResolveFilePath with: %s\n", decodedPath)
	resolvedPath, err := h.fileService.ResolveFilePath(decodedPath)
	if err != nil {
		logger.Error("Failed to resolve file path", zap.String("path", decodedPath), zap.Error(err))
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": fmt.Sprintf("Failed to resolve file path: %s", decodedPath),
			"error":   err.Error(),
		})
		return
	}

	logger.Info("Resolved file path", zap.String("original", decodedPath), zap.String("resolved", resolvedPath))
	fmt.Printf("[HANDLER DEBUG] Resolved path: %s\n", resolvedPath)

	// 调用服务层获取文件内容
	content, err := h.fileService.GetFileContent(resolvedPath)
	if err != nil {
		logger.Error("Failed to get file content", zap.String("path", resolvedPath), zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to get file content",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "File content retrieved successfully",
		"data": gin.H{
			"content":       content,
			"path":          decodedPath,
			"resolved_path": resolvedPath,
		},
	})
}

// GetPointByID 处理根据点ID获取点详细信息请求，用于验证数据存储
func (h *SystemHandler) GetPointByID(c *gin.Context) {
	// 获取点ID参数
	pointID := c.Param("id")
	if pointID == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Point ID is required",
		})
		return
	}

	// 调用服务层获取点详细信息
	result, err := h.fileService.GetPointByID(c.Request.Context(), pointID)
	if err != nil {
		logger.Error("Failed to get point by ID", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to get point by ID",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Point retrieved successfully",
		"data":    result,
	})
}
